package cn.jbolt.common.service;

import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class FtpService {
	//ftp登陆地址
			private String ftpHost;
			//ftp登录名
			private String ftpUserName;
			//ftp密码
			private String ftpPassWord;
			//ftp端口号
			private int ftpPort=21;
			//ftp本地下载路径
			private String localFilePath;
			private String ftpFilePath;
			//ftp超时时间，单位秒
			private int timeOut=100000;
			//ftp通道类型
			private String channelType="sftp";
			
			public String getFtpHost() {
				return ftpHost;
			}
			public void setFtpHost(String ftpHost) {
				this.ftpHost = ftpHost;
			}
			public String getFtpUserName() {
				return ftpUserName;
			}
			public void setFtpUserName(String ftpUserName) {
				this.ftpUserName = ftpUserName;
			}
			public String getFtpPassWord() {
				return ftpPassWord;
			}
			public void setFtpPassWord(String ftpPassWord) {
				this.ftpPassWord = ftpPassWord;
			}
			public int getFtpPort() {
				return ftpPort;
			}
			public void setFtpPort(int ftpPort) {
				this.ftpPort = ftpPort;
			}
			public String getLocalFilePath() {
				return localFilePath;
			}
			public void setLocalFilePath(String localFilePath) {
				this.localFilePath = localFilePath;
			}
			public String getFtpFilePath() {
				return ftpFilePath;
			}
			public void setFtpFilePath(String ftpFilePath) {
				this.ftpFilePath = ftpFilePath;
			}
			public int getTimeOut() {
				return timeOut;
			}
			public void setTimeOut(int timeOut) {
				this.timeOut = timeOut;
			}
			public String getChannelType() {
				return channelType;
			}
			public void setChannelType(String channelType) {
				this.channelType = channelType;
			}
			public boolean startDownload() throws JSchException{
				Session session=null;
				Channel channel=null;
				JSch jsch=new JSch();
				session=jsch.getSession(ftpUserName, ftpHost, ftpPort);
				session.setPassword(ftpPassWord);
				session.setTimeout(timeOut);
				Properties config=new Properties();
				config.put("StrictHostKeyChecking", "no");
				session.setConfig(config);
				session.connect();
				channel=session.openChannel(channelType);
				channel.connect();
//				if (channelType=="sftp") {
					ChannelSftp chSftp=(ChannelSftp) channel;
//				}else{
//					ChannelSftp chSftp=(ChannelSftp) channel;
//				}
				try {
					chSftp.get(ftpFilePath, localFilePath);
				} catch (Exception e) {
					e.printStackTrace();
					return false;
					// logger.info("download error.");
				} finally {
					chSftp.quit();
					channel.disconnect();
					session.disconnect();
					return true;
				}
			}
}
